package com.webapp.controller;

import java.io.IOException;
import java.sql.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.webapp.model.Advertisement;
import com.webapp.model.AdvertisementModel;
import com.webapp.model.Circle;
import com.webapp.model.CircleModel;
import com.webapp.model.Person;
import com.webapp.model.User;

public class AdvertisementServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	
	public AdvertisementServlet()
	{
		super();
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// get session
		HttpSession session = request.getSession();
		
		// get the person object from session
		Person person = (Person)session.getAttribute("UserObject");
//		String x = person.getType().toLowerCase();
//		User myUser = myUser = (User) person;
		int SSN = person.getSSN();
		
		
		// get parameters from form in request object
//		String fenceName = (String)request.getParameter("fenceNameTxt");
//		String fenceType = (String)request.getParameter("fenceTypeTxt");
		
		// create and populate new advertisement
		Advertisement advertisement = new Advertisement();
		advertisement.setAdvertisementId(0);
		advertisement.setEmployeeId(SSN);
		advertisement.setType(request.getParameter("advertisementType"));
		advertisement.setDate((String)request.getAttribute("advertisementDate"));
		advertisement.setCompany(request.getParameter("advertisementCompany"));
		advertisement.setItemName(request.getParameter("advertisementItem"));
		advertisement.setContent(request.getParameter("advertisement"));
		advertisement.setPrice(Integer.parseInt(request.getParameter("advertisementPrice")));
		advertisement.setUnits(Integer.parseInt(request.getParameter("advertisementUnits")));
		
		// get the advertisement model and send it off!
		AdvertisementModel am = new AdvertisementModel();
		if(am.createAdvertisement(advertisement) == true) {
			
			// get the list of advertisement for user
			List advertisementsByEmployee = am.getAdvertisementsByEmployee(SSN);
			
			// update advertisement in session and redirect
			session.setAttribute("Advertisement", advertisementsByEmployee);
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/ManageAdvertisements.jsp?advertisement=created");
			dispatcher.forward(request, response);	
		} else {
			// redirect and say no go
			response.sendRedirect("ManageAdvertisements.jsp?advertisement=error");
		}
	}
}
